package com.ht.medicaltreatment.activity

import android.graphics.Color
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.StringUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.githang.statusbar.StatusBarCompat

import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.BusTag
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.LoseAdapter
import com.ht.medicaltreatment.adapter.MoreAdapter
import com.ht.medicaltreatment.adapter.ScanAdapter
import com.ht.medicaltreatment.bean.ScallSDKListBean
import com.ht.medicaltreatment.utils.EventBusUtils
import com.ht.medicaltreatment.utils.ScanUtils
import com.ht.medicaltreatment.utils.SoundUtils
import com.ht.medicaltreatment.view.ReplaceDialog
import com.ht.medicaltreatment.viewmodel.ScanViewModel
import com.xgst.lib.utils.showToast
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.android.synthetic.main.activity_scall_layout.btnAgain
import kotlinx.android.synthetic.main.activity_scall_layout.btnPositive
import kotlinx.android.synthetic.main.activity_scall_layout.btnStopScan
import kotlinx.android.synthetic.main.activity_scall_layout.imgLose
import kotlinx.android.synthetic.main.activity_scall_layout.imgMore
import kotlinx.android.synthetic.main.activity_scall_layout.imgState
import kotlinx.android.synthetic.main.activity_scall_layout.recyclerView
import kotlinx.android.synthetic.main.activity_scall_layout.recyclerViewLose
import kotlinx.android.synthetic.main.activity_scall_layout.recyclerViewMore
import kotlinx.android.synthetic.main.activity_scall_layout.tvFour
import kotlinx.android.synthetic.main.activity_scall_layout.tvLoseCount
import kotlinx.android.synthetic.main.activity_scall_layout.tvMoreCount
import kotlinx.android.synthetic.main.activity_scall_layout.tvNullCount
import kotlinx.android.synthetic.main.activity_scall_layout.tvOriginalCount
import kotlinx.android.synthetic.main.activity_scall_layout.tvOutCount
import kotlinx.android.synthetic.main.activity_scall_layout.tvRealCount
import kotlinx.android.synthetic.main.activity_scall_layout.tvSix
import kotlinx.android.synthetic.main.activity_scall_layout.tvState
import kotlinx.android.synthetic.main.activity_scall_layout.tvTitleInfo

class ScanActivity : BaseActivity(), OnItemClickListener {
    private var startFlag : Boolean = false
    private var isOpenLose : Boolean = false
    private var isImgMore : Boolean = false
    //盒子的UID
    private lateinit var mBoxUid:String
    private var transportSampleBoxId = ""
    private lateinit var scanAdapter:ScanAdapter
    //表格集合
    private val list = mutableListOf<ScallSDKListBean>()
    //多出来的试管放在这个集合中
    private val errorList = mutableListOf<String>()
    //空位置
    private val nullList = mutableListOf<ScallSDKListBean>()
    //扫描出来的uid
    private val scanList = mutableListOf<String>()
    //实际扫描到的数量
    private var realCount = 0
    //缺失的试管
    private var loseCountList = mutableListOf<ScallSDKListBean>()
    //用来记录每个uid的位置
    private val mUidMap = mutableMapOf<String,ScallSDKListBean>()
    private lateinit var dialog : ReplaceDialog
    private var isReplace = false
    private val mViewModel by viewModels<ScanViewModel>()

    private val loseAdapter = LoseAdapter()
    private val moreAdapter = MoreAdapter()
    private var orderId = 0
    private lateinit var from:String
    var isFirstScan = true

    override fun getLayoutId() = R.layout.activity_scall_layout

    override fun init() {
        StatusBarCompat.setStatusBarColor(this,getColor(R.color.white),true)

        dialog = ReplaceDialog(this)
        mBoxUid = intent.getStringExtra("uid")?:""
        //转入:TRANSPORTTO   转出:TRANSPORT
        from = intent.getStringExtra("from")?:"TRANSPORT"
        orderId = intent.getIntExtra("orderId",0)
        scanAdapter = ScanAdapter()

        recyclerViewLose.layoutManager = LinearLayoutManager(this)
        recyclerViewLose.adapter = loseAdapter

        recyclerViewMore.layoutManager = LinearLayoutManager(this)
        recyclerViewMore.adapter = moreAdapter
        loseAdapter.setOnItemClickListener(this)
        moreAdapter.setOnItemClickListener(this)

        ScanUtils.init(onInitResult = {
            btnStopScan.isEnabled = true
            btnStopScan.setBackgroundColor(getColor(R.color.blue))
        })

        initData(false)
        initClick()
    }

    /**
     * 获取数据
     */
    private fun initData(isReset:Boolean) {
        showProgress()
        tvState.setText("样品待检验…")
        tvState.setTextColor(getColor(R.color.color22_50))
        mViewModel.scanData(mBoxUid, "$orderId",from, {
            recyclerView.layoutManager = GridLayoutManager(this, it.structureCol)
            recyclerView.adapter = scanAdapter
            //转运样本盒id
            transportSampleBoxId  = "${it.id}"
            tvTitleInfo.text = "实际盘点样本信息：${it.name}"
            list.clear()
            mUidMap.clear()

            it.sampleVOList?.forEach {
                list += ScallSDKListBean(it.location, it.uid, it.transportRfidSampleId, it.status, 0,it.name)
                if (it.uid != null) {
                    mUidMap.put(it.uid,
                        ScallSDKListBean(it.location, it.uid, it.transportRfidSampleId, it.status, 1,it.name))
                }
            }
            tvOriginalCount.text = "${mUidMap.size}"
            scanAdapter.setNewInstance(list)
            dismissProgress()
            if(isReset){
                showToast("开始扫描")
                startScan()
            }
        }, {
            dismissProgress()
            showToast(it)
        })
    }

    private fun initClick() {
        //缺失样本数量
        tvFour.setOnClickListener {
            if(isOpenLose){
                imgLose.rotation = 0f
                recyclerViewLose.visibility = View.GONE
            }else{
                imgLose.rotation = 90f
                recyclerViewLose.visibility = View.VISIBLE
            }
            isOpenLose = !isOpenLose
        }

        //不属于该样本盒的样本数量
        tvSix.setOnClickListener {
            if(isImgMore){
                imgMore.rotation = 0f
                recyclerViewMore.visibility = View.GONE
            }else{
                imgMore.rotation = 90f
                recyclerViewMore.visibility = View.VISIBLE
            }
            isImgMore = !isImgMore
        }

        dialog.setOnDismissListener {
            ScanUtils.close()
            startFlag = false
        }

        //确认
        btnPositive.setOnClickListener {
            if(scanList.size == 0){
                showToast("请先开始盘点")
                return@setOnClickListener
            }
            if(loseCountList.size > 0 || errorList.size > 0){
                showToast("盘点检验有误")
                return@setOnClickListener
            }
            showProgress()
            mViewModel.submit(transportSampleBoxId,{
                dismissProgress()
                showToast("提交成功")
                if(from == "TRANSPORTTO"){
                    //转入
                    EventBusUtils.post(BusTag.IN)
                }
                btnPositive.text = "已提交"
                btnPositive.isEnabled = false
                btnPositive.setBackgroundColor(getColor(R.color.color97))

                btnAgain.isEnabled = false
                btnAgain.setBackgroundColor(getColor(R.color.color97))
                finish()
            },{
                dismissProgress()
                showToast(it)
            })
        }

        //重新核验
        btnAgain.setOnClickListener {
            reset()
        }

        //开始扫描 - 停止扫描
        btnStopScan.setOnClickListener {
            if(isFirstScan){
                startScan()
                isFirstScan = false
                return@setOnClickListener
            }
            if(startFlag){
                //停止扫描
                ScanUtils.close()
                startFlag = false
                checkScanResult()
                changeBtnText()
            }else{
                //开始扫描 - 重新核验
                reset()
            }
        }
    }

    private fun reset() {
        tvRealCount.setText("0")
        tvOutCount.setText("0")
        tvLoseCount.setText("0")
        tvNullCount.setText("0")
        tvMoreCount.setText("0")
        isReplace = false
        scanList.clear()
        loseCountList.clear()
        errorList.clear()
        imgState.visibility = View.GONE
        loseAdapter.setNewInstance(null)
        moreAdapter.setNewInstance(null)
        initData(true)
    }

    private var disposable: Disposable?=null

    //开始扫描
    private fun startScan(){
        startFlag = true
        changeBtnText()
        ScanUtils.open { newUID ->
            if(!StringUtils.isEmpty(newUID)){
                if(isReplace){
                    ScanUtils.close()
                    startFlag = false
                    ScanUtils.resetItem(newUID)
                    dialog.setUID(newUID)
                    return@open
                }

                SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                scanList += newUID
                //直接对着样本盒扫描，所以要排除样本盒uid
                if(newUID != mBoxUid){
                    val value = mUidMap[newUID]
                    if(value == null){
                        //不是这个样本盒内的管子
                        errorList += newUID!!
                        tvMoreCount.text = "${errorList.size}"
                    }else{
                        //扫描到的试管，变蓝
                        scanAdapter.setData(value.location-1,value)
                    }
                }
            }
        }
    }

    /**
     * 修改开始扫描按钮的状态
     */
    private fun changeBtnText() {
        if(startFlag){
            btnStopScan.text = "停止扫描"
            btnStopScan.setBackgroundColor(Color.RED)
        }else{
            btnStopScan.text = "开始扫描"
            btnStopScan.setBackgroundColor(getColor(R.color.blue))
        }
    }

    /**
     * 倒计时结束后，开始检测扫描结果
     */
    private fun checkScanResult() {
        nullList.clear()
        loseCountList.clear()
        realCount = 0
        val adapterData = scanAdapter.data
        adapterData.forEach {
            if(it.type == 0){
                val bean = ScallSDKListBean(it.location,
                    it.uid,it.transportRfidSampleId,it.isExist,3,it.name)
                nullList += bean
                if(it.uid != null){
                    //缺失了，没有扫描到这个试管
                    loseCountList += bean
                    tvLoseCount.text = "${loseCountList.size}"
                    //LogUtils.i("缺失的位置 "+it.location)
                }
            }else{
                realCount++
            }
        }

        if(loseCountList.size > 0){
            //如果有缺失，其他空位置全部变红
            adapterData.forEach {
                if(it.type == 0){
                    val bean = ScallSDKListBean(it.location,
                        it.uid,it.transportRfidSampleId,it.isExist,3,it.name)
                    scanAdapter.setData(it.location-1,bean)
                }
            }
        }

        tvLoseCount.text = "${loseCountList.size}"
        loseAdapter.setNewInstance(loseCountList)

        if(errorList.size > 0 && nullList.size > 0){
            //有多出来的试管，并且也有空余的格子
            nullList.forEach {
                scanAdapter.setData(it.location-1,it)
            }
            moreAdapter.setNewInstance(errorList)
        }

        tvRealCount.text = "$realCount"

        imgState.visibility = View.VISIBLE
        if(errorList.size > 0 || loseCountList.size > 0){
            tvState.text = "检验异常"
            imgState.setBackgroundResource(R.drawable.icon_check_error)
            tvState.setTextColor(getColor(R.color.yellow))
        }else{
            tvState.text = "检验无误"
            imgState.setBackgroundResource(R.drawable.icon_check_ok)
            tvState.setTextColor(getColor(R.color.green))
        }
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        if (adapter is LoseAdapter){
            isReplace = true
            val bean = adapter.data.get(position)

            startScan()
            //替换芯片
            dialog.showDialog(position,{newUID,position ->
                dialog.dismiss()
                showProgress()
                isReplace = false
                LogUtils.i("替换 ",bean.transportRfidSampleId,newUID)
                mViewModel.replaceUID("${bean.transportRfidSampleId}",newUID,{
                    dismissProgress()
                    if(mUidMap.containsKey(it)){
                        val location = mUidMap[it]?.location
                        LogUtils.i("替换位置 $location")
                        scanAdapter.setData(location!!-1,mUidMap[it]!!)
                    }
                },{
                    dismissProgress()
                    showToast(it)
                })
            })
        }else if(adapter is MoreAdapter){
            //不属于该样本盒，获取每个试管的名字
            showProgress()
            mViewModel.searchName(errorList,{
                dismissProgress()
                moreAdapter.setNewInstance(it)
            },{
                dismissProgress()
                showToast(it)
            })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if(disposable?.isDisposed == false){
            disposable?.dispose()
        }
        ScanUtils.close()
        startFlag = false
    }
}